﻿using System;
using System.Collections.Generic;
using System.Text;

namespace CSharpExt.Text
{
    public static class DateTimeParser
    {
        public static DateTime Parse(String date, String time)
        {
            if (String.IsNullOrEmpty(time))
                return Parse(date);
            if (String.IsNullOrEmpty(date))
                return Parse(time);
            else
                return Parse(date + " " + time);
        }

        public static DateTime Parse(String dateTime)
        {
            if (dateTime.Length < 19)
            {
                if (dateTime.IndexOf(':') != -1)
                    return parseTime(dateTime);
                else
                    return parseDate(dateTime);
            }
            else
            {
                return parseDateTime(dateTime);
            }
        }

        /// <summary>
        /// HH:mm:ss
        /// </summary>
        private static DateTime parseTime(String time)
        {
            String[] parts = time.Split(':');
            DateTime now = DateTime.Now;
            return new DateTime(
                now.Year,
                now.Month,
                now.Day,
                int.Parse(parts[0]),
                int.Parse(parts[1]),
                int.Parse(parts[2]));
        }

        private static DateTime parseDate(String date)
        {
            String[] parts = date.Split('-', '/');
            DateTime now = DateTime.Now + new TimeSpan(0, 0, 0, 10);
            return new DateTime(
                int.Parse(parts[0]),
                int.Parse(parts[1]),
                int.Parse(parts[2]),
                now.Hour,
                now.Minute,
                now.Second);
        }

        private static DateTime parseDateTime(String dateTime)
        {
            dateTime = dateTime.Replace(' ', 'T').Replace('/', '-');
            return DateTime.Parse(dateTime);
        }

    }
}
